# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://opensource.org/licenses/MIT
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
specific language governing permissions and limitations under the License.
"""
from django.http import JsonResponse
from django.shortcuts import render
import json
from django.views.decorators.csrf import csrf_exempt
from blueapps.account.decorators import login_exempt

from blueking.component.shortcuts import get_client_by_request


# 开发框架中通过中间件默认是需要登录态的，如有不需要登录的，可添加装饰器login_exempt
# 装饰器引入 from blueapps.account.decorators import login_exempt
def home(request):
    """
    首页
    """
    return render(request, "home_application/index_home.html")


def dev_guide(request):
    """
    开发指引
    """
    return render(request, "home_application/dev_guide.html")


def contact(request):
    """
    联系页
    """
    return render(request, "home_application/contact.html")


# 开发样例，在这里实现了【查询业务列表接口】
def get_bizs_list(request):
    """
    获取业务列表
    """
    # 从环境配置获取APP信息，从request获取当前用户信息
    client = get_client_by_request(request)
    # 请求参数
    kwargs = {
        "fields": [
            "bk_biz_id",
            "bk_biz_name"
        ],
        # 社区版环境中业务数量有限，故不考虑分页情况
        "page": {
            "start": 0,
            "limit": 10,
            "sort": ""
        }
    }
    # 这里需要填写对应的组件API的入口地址
    result = client.cc.search_business(kwargs)
    return JsonResponse(result)


# 请仿照此前的接口，实现查询集群列表接口
def get_sets_list(request):
    client = get_client_by_request(request)

    # 构造请求参数
    kwargs = {
        "bk_biz_id": request.GET.get('bk_biz_id'),  # 从 request.GET 中获取 bk_biz_id 参数
        "fields": [
            "bk_set_id",
            "bk_set_name",
            "bk_biz_id",
            "bk_created_at",
            "bk_supplier_account"
        ],
    }

    # 调用蓝鲸配置平台 API 查询集群(set) 列表
    result = client.cc.search_set(kwargs)

    # 返回 JSON 响应
    return JsonResponse(result)


def get_modules_list(request):
    """
    根据业务ID和集群ID，查询对应的下辖模块列表。

    请求方式：GET
    请求参数：
        - bk_biz_id: 业务ID（必填）
        - bk_set_id: 集群ID（必填）

    返回：
        - result: 查询结果，以 JSON 格式返回
    """
    # 获取客户端对象（假设封装了蓝鲸API的请求）
    client = get_client_by_request(request)

    # 从请求中获取参数
    bk_biz_id = request.GET.get('bk_biz_id')
    bk_set_id = request.GET.get('bk_set_id')

    # 构造请求参数
    kwargs = {
        "bk_biz_id": bk_biz_id,
        "bk_set_id": bk_set_id,
        "fields": [
            "bk_module_id",
            "bk_module_name",
            "bk_set_id",
            "bk_biz_id",
            "bk_created_at",
            "bk_supplier_account"
        ],
    }

    # 调用蓝鲸配置平台 API 查询模块列表
    result = client.cc.search_module(kwargs)

    # 返回 JSON 响应
    return JsonResponse(result)


def get_hosts_list(request):
    """
    根据传递的查询条件，包括但不限于（业务ID、集群ID、模块ID、主机ID、主机维护人）
    查询主机列表
    """
    client = get_client_by_request(request)
    # 构造请求参数
    kwargs = {
        "bk_biz_id": request.GET.get("bk_biz_id"),
        # TODO 待优化项：学有余力的同学可尝试实现分页
        "page": {
            "start": 0,
            "limit": 100,
        },
        "fields": [
            "bk_host_id",          # 主机ID
            "bk_cloud_id",         # 云区域ID
            "bk_host_innerip",     # 主机内网IP
            "bk_os_type",          # 操作系统类型
            "bk_mac",              # 主机MAC地址
            "operator",            # 操作人
            "bk_bak_operator"      # 备份维护人
        ]
    }

    # 添加可选参数：集群ID（bk_set_id）
    if request.GET.get("bk_set_id"):
        # 注意：接口要求为 bk_set_ids 且为整数数组
        kwargs["bk_set_ids"] = [int(request.GET.get("bk_set_id"))]  # 注意这里的数据结构，仔细阅读接口文档

    # 添加可选参数：模块ID（bk_module_id）
    if request.GET.get("bk_module_id"):
        # 注意：接口要求为 bk_module_ids 且为整数数组
        kwargs["bk_module_ids"] = [int(request.GET.get("bk_module_id"))]  # 注意这里的数据结构，仔细阅读接口文档

    # 调用配置平台 API 查询主机列表
    result = client.cc.list_biz_hosts(kwargs)
    print('API返回结果:', result)  # 调试信息
    return JsonResponse(result)


def get_host_detail(request):
    """
    根据主机ID，查询主机详情信息
    """
    client = get_client_by_request(request)
    kwargs = {
        "bk_host_id": request.GET.get("bk_host_id")
    }
    result = client.cc.get_host_base_info(kwargs)
    return JsonResponse(result)


def get_projects_list(request):
    """
    获取项目列表
    """
    client = get_client_by_request(request)
    # 从GET请求中获取参数
    page = request.GET.get('page', 1)
    page_size = request.GET.get('page_size', 10)
    search_key = request.GET.get('search_key', '')
    search_field = request.GET.get('search_field', 'bk_biz_name')  # 默认按名称搜索
    
    print('接收到的请求参数:', {
        'page': page,
        'page_size': page_size,
        'search_key': search_key,
        'search_field': search_field
    })
    
    # 构造请求参数
    kwargs = {
        "page": {
            "start": (int(page) - 1) * int(page_size),
            "limit": int(page_size),
            "sort": "id",
            "enable_count": True
        }
    }
    
    # 如果有搜索关键字，添加filter条件
    if search_key:
        kwargs["filter"] = {
            "condition": "AND",
            "rules": [{
                "field": search_field,
                "operator": "equal",
                "value": search_key
            }]
        }
    
    print('发送给BK API的参数:', kwargs)
    
    result = client.cc.list_project(kwargs)
    print('API返回结果:', result)
    
    return JsonResponse(result)


@csrf_exempt
@login_exempt
def create_project(request):
    """
    创建项目
    """
    client = get_client_by_request(request)
    # 从POST请求中获取参数
    data = json.loads(request.body)
    print('接收到的请求数据:', data)  # 调试信息

    # 构造请求参数
    kwargs = {
        "data": {
            "bk_biz_name": data.get('bk_project_name'),
            "bk_biz_code": data.get('bk_project_code'),
            "bk_biz_desc": data.get('bk_project_desc'),
            "bk_biz_type": data.get('bk_project_type', 'other'),
            "bk_biz_sec_lvl": data.get('bk_project_sec_lvl', 'public'),
            "bk_biz_owner": data.get('bk_project_owner'),
            "bk_biz_team": data.get('bk_project_team', []),
        }
    }
    print('发送给BK API的参数:', kwargs)  # 调试信息

    result = client.cc.batch_create_project(kwargs)
    print('API返回结果:', result)  # 调试信息
    return JsonResponse(result)


def delete_projects(request):
    """
    批量删除项目
    """
    client = get_client_by_request(request)
    data = json.loads(request.body)
    kwargs = {
        "bk_biz_id": data.get('bk_biz_id'),
        "bk_biz_ids": data.get('ids')
    }
    result = client.cc.batch_delete_project(kwargs)
    return JsonResponse(result)

# 获取服务模板列表
def get_service_templates_list(request):
    """
    获取服务模板列表
    """
    print('接收到的请求参数:', request.GET)
    try:
        # 验证必要参数
        bk_biz_id = request.GET.get('bk_biz_id')
        if not bk_biz_id:
            return JsonResponse({
                'result': False,
                'code': 1,
                'message': '缺少必要参数: bk_biz_id'
            }, status=400)

        client = get_client_by_request(request)
        # 构造请求参数
        kwargs = {
            "bk_biz_id": int(bk_biz_id),  # 确保转换为整数
            "page": {
                "start": (int(request.GET.get('page', 1)) - 1) * int(request.GET.get('page_size', 10)),
                "limit": int(request.GET.get('page_size', 10)),
                "sort": "-name",
                "enable_count": True
            }
        }
        
        # 如果有搜索关键字，添加filter条件
        search = request.GET.get('search')
        if search and len(search) > 0:
            kwargs["search"] = search
            kwargs["is_exact"] = True
        else:
            kwargs.pop("search", None)
            kwargs.pop("is_exact", None)
        
        # 如果有分类ID，添加分类过滤
        category_id = request.GET.get('category_id')
        if category_id:
            kwargs["service_category_id"] = int(category_id)
        
        print('发送给BK API的参数:', kwargs)
        
        result = client.cc.list_service_template(kwargs)
        print('API返回结果:', result)
        
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)


@csrf_exempt
@login_exempt
def create_service_template(request):
    """
    创建服务模板
    """
    try:
        data = json.loads(request.body)
        print('接收到的请求数据:', data)
        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": int(data.get('bk_biz_id')),
            "name": data.get('name'),
            "service_category_id": int(data.get('service_category_id'))
        }
        print('发送给BK API的参数:', kwargs)
        result = client.cc.create_service_template(kwargs)
        print('API返回结果:', result)
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)


@csrf_exempt
@login_exempt
def update_service_template(request):
    """
    更新服务模板
    """
    client = get_client_by_request(request)
    data = json.loads(request.body)
    print('接收到的请求数据:', data) # 调试信息

    kwargs = {
        "data": {
            "id": data.get('bk_template_id'), # Assuming bk_template_id is used for identification
            "bk_template_name": data.get('bk_template_name'),
            "bk_template_desc": data.get('bk_template_desc'),
            "bk_template_type": data.get('bk_template_type'),
            "bk_template_owner": data.get('bk_template_owner'),
            "bk_template_team": data.get('bk_template_team', [])
        }
    }
    print('发送给BK API的参数:', kwargs) # 调试信息

    result = client.cc.update_service_template(kwargs)
    print('API返回结果:', result) # 调试信息
    return JsonResponse(result)


@csrf_exempt
@login_exempt
def delete_service_template(request):
    """
    删除服务模板
    """
    try:
        data = json.loads(request.body)
        print('接收到的请求数据:', data)
        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": int(data.get('bk_biz_id')),
            "service_template_id": int(data.get('service_template_id'))
        }
        print('发送给BK API的参数:', kwargs)
        result = client.cc.delete_service_template(kwargs)
        print('API返回结果:', result)
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)

@csrf_exempt
@login_exempt
def get_service_categories_list(request):
    """
    获取服务分类列表
    """
    print('接收到的请求参数:', request.GET)
    try:
        # 验证必要参数
        bk_biz_id = request.GET.get('bk_biz_id')
        if not bk_biz_id:
            return JsonResponse({
                'result': False,
                'code': 1,
                'message': '缺少必要参数: bk_biz_id'
            }, status=400)

        client = get_client_by_request(request)
        kwargs = {
            "bk_biz_id": int(bk_biz_id)  # 确保转换为整数
        }
        result = client.cc.list_service_category(kwargs)
        print('API返回结果:', result)
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)

@csrf_exempt
@login_exempt
def get_cloud_areas(request):
    """
    获取云区域列表
    """
    print('接收到的请求参数:', request.GET)
    try:
        client = get_client_by_request(request)
        # 构造请求参数
        kwargs = {
            "page": {
                "start": (int(request.GET.get('page', 1)) - 1) * int(request.GET.get('page_size', 10)),
                "limit": int(request.GET.get('page_size', 10))
            }
        }
        
        # 如果有搜索关键字，添加filter条件
        search = request.GET.get('search')
        if search and len(search) > 0:
            kwargs["condition"] = {
                "bk_cloud_name": search
            }
        
        print('发送给BK API的参数:', kwargs)
        
        result = client.cc.search_cloud_area(kwargs)
        print('API返回结果:', result)
        
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)

@csrf_exempt
@login_exempt
def create_cloud_area(request):
    """
    创建云区域
    """
    print('接收到的请求参数:', request.body)
    try:
        data = json.loads(request.body)
        name = data.get('name')
        description = data.get('description', '')

        if not name:
            return JsonResponse({
                'result': False,
                'code': 1,
                'message': '云区域名称不能为空'
            }, status=400)

        client = get_client_by_request(request)
        kwargs = {
            "bk_cloud_name": name,
            "bk_cloud_desc": description
        }
        
        print('发送给BK API的参数:', kwargs)
        
        result = client.cc.create_cloud_area(kwargs)
        print('API返回结果:', result)
        
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)

@csrf_exempt
@login_exempt
def update_cloud_area(request):
    """
    更新云区域
    """
    print('接收到的请求参数:', request.body)
    try:
        data = json.loads(request.body)
        area_id = data.get('id')
        name = data.get('name')
        description = data.get('description', '')

        if not area_id or not name:
            return JsonResponse({
                'result': False,
                'code': 1,
                'message': '云区域ID和名称不能为空'
            }, status=400)

        client = get_client_by_request(request)
        kwargs = {
            "bk_cloud_id": int(area_id),
            "bk_cloud_name": name,
            "bk_cloud_desc": description
        }
        
        print('发送给BK API的参数:', kwargs)
        
        result = client.cc.update_cloud_area(kwargs)
        print('API返回结果:', result)
        
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)

@csrf_exempt
@login_exempt
def delete_cloud_area(request):
    """
    删除云区域
    """
    print('接收到的请求参数:', request.body)
    try:
        data = json.loads(request.body)
        area_id = data.get('id')

        if not area_id:
            return JsonResponse({
                'result': False,
                'code': 1,
                'message': '云区域ID不能为空'
            }, status=400)

        client = get_client_by_request(request)
        kwargs = {
            "bk_cloud_id": int(area_id)
        }
        
        print('发送给BK API的参数:', kwargs)
        
        result = client.cc.delete_cloud_area(kwargs)
        print('API返回结果:', result)
        
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)

@csrf_exempt
@login_exempt
def get_service_instances(request):
    """
    获取服务实例列表
    请求参数：
        - bk_biz_id: 业务ID（必填）
        - bk_module_id: 模块ID（选填）
        - page: 分页参数（选填）
        - search_key: 名字过滤参数（选填）
    """
    print('接收到的请求参数:', request.GET)
    try:
        # 验证必要参数
        bk_biz_id = request.GET.get('bk_biz_id')
        if not bk_biz_id:
            return JsonResponse({
                'result': False,
                'code': 1,
                'message': '缺少必要参数: bk_biz_id'
            }, status=400)

        client = get_client_by_request(request)
        # 构造请求参数
        kwargs = {
            "bk_biz_id": int(bk_biz_id),
            "page": {
                "start": (int(request.GET.get('page', 1)) - 1) * int(request.GET.get('page_size', 10)),
                "limit": int(request.GET.get('page_size', 10))
            }
        }
        
        # 添加模块ID参数（如果提供）
        bk_module_id = request.GET.get('bk_module_id')
        if bk_module_id and bk_module_id != '':
            kwargs["bk_module_id"] = int(bk_module_id)
        
        # 添加搜索关键字（如果提供）
        search_key = request.GET.get('search_key')
        if search_key and len(search_key) > 0:
            kwargs["search_key"] = search_key
        
        print('发送给BK API的参数:', kwargs)
        
        result = client.cc.list_service_instance(kwargs)
        print('API返回结果:', result)
        
        return JsonResponse(result)
    except Exception as e:
        print('API错误:', str(e))
        return JsonResponse({
            'result': False,
            'code': 1,
            'message': str(e)
        }, status=500)


